<script setup lang="ts">
import { setToken } from '@/utils/auth';
import service from '@/utils/https';
import { ElMessage, type FormInstance, type FormRules } from 'element-plus';
import { ref } from 'vue';
import { useRouter } from 'vue-router';

interface FormData {
  mobile:string
  code:string
  checked:boolean
}
interface ServiceRes<T> {
  message: string
  data: T
}
interface formRes {
  token: string
  refresh_token: string
}

const formRef = ref<FormInstance>()


const checkedBox = (rule:object,value:boolean,callback:(error?:Error)=>void)=>{
  if (value) {
    callback()
  }else{
    callback(new Error('请阅读并同意用户协议和隐私条款'))
  }
}

const formRules = ref<FormRules<FormData>>({
  mobile: [
    { required: true, message: '请输入手机号', trigger: 'blur' },
  ],
  code: [
    { required: true, message: '请输入验证码', trigger: 'blur' },
  ],
  checked:[
    {validator:checkedBox,trigger:'change'}
  ]
})

const formData = ref<FormData>({
  mobile: '13200000000',
  code: '246810',
  checked:false
})

const router = useRouter()
const onSubmit = () => {
  formRef.value?.validate(async (valid) => {
    if (valid) {
      const res = await service.post<ServiceRes<formRes>>('/v1_0/authorizations', formData.value)
      setToken(res.data.data.token)
      router.push('/')
      ElMessage.success('登录成功')
    } else {
      ElMessage.error('登录失败')
    }
  })
}
</script>
<template>
  <div class="contation">
    <el-card>
      <img src="@/assets/images/logo.png" class="logo" alt="" />
      <!-- 表单 -->
      <el-form ref="formRef" :model="formData" :rules="formRules">
        <el-form-item prop="mobile">
          <el-input v-model="formData.mobile" placeholder="请输入用户名" />
        </el-form-item>

        <el-form-item prop="code">
          <el-input v-model="formData.code" placeholder="请输入密码" show-password/>
        </el-form-item>

        <el-form-item prop="checked">
          <el-checkbox v-model="formData.checked">我已阅读并同意「用户协议」和「隐私条款」</el-checkbox>
        </el-form-item>

        <el-form-item>
          <el-button @click="onSubmit" type="primary">登 录</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<style lang="less" scoped>
.contation {
  width: 100%;
  height: 100%;
  position: absolute;
  left: 0;
  top: 0;
  background: url('@/assets/images/login.png');

  .el-card {
    width: 440px;
    height: 380px;
    position: absolute;
    left: 50%;
    top: 50%;
    transform: translate(-50%, -50%);
    box-shadow: 0 0 50px rgba(0, 0, 0, 0.1);

    .logo {
      width: 200px;
      display: block;
      margin: 0 auto 20px;
    }

    .el-form {
      padding: 0 20px;

      .el-button {
        width: 100%;
      }
    }
  }
}
</style>
